﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability_Management.Domain;
using Traceability_Management.ErrorCode;
using Traceability_Management.Infrastructure.Interfaces;
using Traceability_Management.Read.Api.Application.Command.RabitsWay;
using Traceability_Management.Read.Api.Dto;

namespace Traceability_Management.Read.Api.Application.CommandHandler.RabitsWay
{
    public class ShowRabitsCommandHandler : IRequestHandler<ShowRabitsCommand, ApiResult<List<RabitDto>>>
    {
        IBaseReponsitory<Rabits> Rabits;
        IBaseReponsitory<Shop_Table> Shop_Table;

        public ShowRabitsCommandHandler(IBaseReponsitory<Rabits> Rabits, IBaseReponsitory<Shop_Table> Shop_Table)
        {
            this.Rabits = Rabits;
            this.Shop_Table = Shop_Table;
        }

        public async Task<ApiResult<List<RabitDto>>> Handle(ShowRabitsCommand request, CancellationToken cancellationToken)
        {
            var list = from a in Rabits.GetQuery()
                       join b in Shop_Table.GetQuery()
                      on a.SId equals b.Shop_Id
                       select new RabitDto
                       {
                          Rabit_Id = a.Rabit_Id,
                           Shop_Id=a.SId,
                           Shop_Name=b.Shop_Name,
                           Rabit_Batch=a.Rabit_Batch,
                           Rabit_Shelflife=a.Rabit_Shelflife,
                           Rabit_Shencan = a.Rabit_Shencan,
                           Rabit_Company=a.Rabit_Company,
                           Rabit_Infomation=a.Rabit_Infomation,
                           Rabit_TitleImg=a.Rabit_TitleImg,
                           Rabit_IsDel=a.Rabit_IsDel,
                           Creater=a.Creater,
                           CreateTime=a.CreateTime,
                           Updater=a.Updater,
                           UpdateTime=a.UpdateTime
                       };


            list = list.OrderByDescending(x => x.Rabit_Id).Where(c => !c.Rabit_IsDel);
            return new ApiResult<List<RabitDto>>
            {
                Code = ApiEnum.Success,
                Message = "查询成功",
                Data = await list.ToListAsync()
            };
        }
    }
}
